<template>
  <div>
    <Drawer :title="title">
      <BaseForm>
        <template #companyId="slotProps">
          <div class="w-full">
            <a-select
              class="w-1/2"
              v-bind="slotProps"
              :options="companyList"
              @change="handleChange"
              placeholder="请选择机构"
            ></a-select>
            <Button class="submitBtn" type="primary" @click="openDrawer({})"
              >新增机构</Button
            >
          </div>
        </template>
      </BaseForm>
    </Drawer>
    <AddInstitutionDrawer ref="AddDictDrawer" @success="() => initData()" />
  </div>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'EditDrawer',
});
import { computed, ref, watch } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { querySave, queryUpdate, getCompanyList } from '../data/api';
import {
  drawerFormSchema,
  handleId,
  idKey,
  companyList,
} from '../data/options';
import { message, Button } from 'ant-design-vue';
import { useThrottleFn } from '@vueuse/core';
import AddDrawer from './addDrawer.vue';

const emit = defineEmits(['success']);
const title = computed(() => {
  return `${handleId.value ? '编辑' : '新增'}报告`;
});

//  初始化机构列表
const initData = async () => {
  console.log('initData');
  let res = await getCompanyList({ handlerName: 'baseCompanyListHandler' });
  companyList.value = res.data.map((item: any) => {
    return {
      label: item.companyName,
      value: item.companyId,
    };
  });
};

// 抽屉提交
const onSubmit = useThrottleFn(async (values: Record<string, any>) => {
  console.log(values);
  const { valid } = await formApi.validate();
  if (!valid) return;
  if (!values[idKey.value]) delete values[idKey.value];
  if (values.fileObj.isChange) {
    values.fileId = values.fileObj.uid;
    values.filePath = values.fileObj.ossPath;
  }
  delete values.fileObj;
  console.log(values);
  const hide = message.loading('提交中...', 0);
  let query = values[idKey.value] ? queryUpdate : querySave;
  let res: any = await query({ ...values, msgTypeId: 1 });
  message.success(res.message);
  hide();
  onSucClose();
}, 1000);

// 新增机构抽屉组件
const [AddInstitutionDrawer, AddDrawerApi] = useVbenDrawer({
  connectedComponent: AddDrawer,
});
const AddDictDrawer = ref(null);

// 打开新增机构抽屉
const openDrawer = (row: any) => {
  AddDrawerApi.setData({
    ...row,
  });
  AddDrawerApi.open();
};

// 抽屉配置
const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-1/2',
  onCancel() {
    drawerApi.close();
  },
  onConfirm: () => onConfirm(),
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      let data = drawerApi.getData();
      handleId.value = data[idKey.value] || '';
      let fileObj = {
        name: data.filePath,
        ossPath: data.filePath,
      };
      data.fileObj = fileObj;
      formApi.setValues({ ...data });
    }
  },
});

// 表单
const [BaseForm, formApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  wrapperClass: 'pl-0 pr-4 pt-4 pb-4',
  schema: drawerFormSchema,
  handleSubmit: onSubmit,
  // 所有表单项
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
});

// 分类选择回调
const handleChange = (value: any) => {
  console.log('handleChange', value);
  formApi.setFieldValue('companyId', value);
};

const onSucClose = () => {
  drawerApi.close();
  emit('success');
};

// 提交按钮
const onConfirm = () => {
  formApi.submitForm();
};
</script>

<style lang="scss" scoped>
.submitBtn {
  margin-left: 30px;
}
</style>
